// express 服务器端web开发框架
// npm i express -D 先安装依赖
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 9000;

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

let brands = [
    {id: 1, name: 'Nike', date: new Date()},
    {id: 2, name: 'Adidas', date: new Date()}
];

// cors, 除此之外推荐使用cors插件，require('cors')
app.use((req, resp, next) => {
    // form表单提交的数据在req.body中，get请求的参数在req.query中
    console.log('req.query => %s, req.params => %s, req.body => %s ', req.query, req.params,req.body);
    resp.header('Access-Control-Allow-Origin', '*');
    next() //继续执行后续代码
});

// 接收post请求
app.post('/save', (req, resp) => {
    brands.push(req.body);
    resp.end();
});
app.post('/del', (req, resp) => {
    let r = brands.some((b, i) => {
        if (b.id == req.body.id) {
            brands.splice(i, 1);
            return true;
        }
    }); // return value true
    console.log('some => ', r);
    resp.end();
});
// 接收get请求
app.get('/list', (req, resp) => {
    let list = brands.filter((b, i) => {
        if (req.query.keyword) {
            return b.name.includes(req.query.keyword);
        }
        return true;
    });
    console.log('list =>', list);
    resp.end(JSON.stringify(list));
});

// 运行 node "vue10 webserver-express.js"
app.listen(port, () => {
    console.log('server run at ', port);
});

